package com.pigdroid.adbsqlite.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Logger;

public class ADBSQLiteDriver implements Driver {
	
	private static ADBSQLiteDriver instance;

	static {
		try {
			if (instance == null) {
				instance = new ADBSQLiteDriver();
			}
			DriverManager.registerDriver(instance);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	
	public boolean acceptsURL(String url) throws SQLException {
		// jdbc:db2://<HOST>:<PORT>/<DATABASE_NAME>
		// jdbc:adbsqlite://com.android.browser:3333/browser2.db
		getPropertiesFromURL(url);
		return true;
	}

	private static Properties getPropertiesFromURL(String url) throws SQLException {
		return getPropertiesFromURL(url, null);
	}
	

	private static Properties getPropertiesFromURL(String url, Properties ret) throws SQLException {
		try {
			StringTokenizer tok = new StringTokenizer(url, "/");
			String jdbcType = tok.nextToken();
			String idSet = tok.nextToken();
			String dbName = tok.nextToken();
			tok = new StringTokenizer(idSet, "/");
			String packagePort = tok.nextToken();
			tok = new StringTokenizer(packagePort, ":");
			String packageName = tok.nextToken();
			String port = tok.nextToken();
			if (!jdbcType.endsWith("adbsqlite:")) {
				throw new Exception("wrong jdbc type");
			}
			if (ret == null) {
				ret = new Properties();
			}
			ret.put("port", port);
			ret.put("packageName", packageName);
			ret.put("dbName", dbName);
		} catch (Exception e) {
			throw new SQLException("The jdbc url must be in format: jdbc:adbsqlite://package:port/dbname");
		}
		return ret;
	}

	
	public Connection connect(String uri, Properties props) throws SQLException {
		return new ADBSQLiteConnection(uri, getPropertiesFromURL(uri, props));
	}

	
	public int getMajorVersion() {
		return 0;
	}

	
	public int getMinorVersion() {
		return 0;
	}

	
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

	
	public DriverPropertyInfo[] getPropertyInfo(String arg0, Properties arg1)
			throws SQLException {
		DriverPropertyInfo[] info = new DriverPropertyInfo[1];
		info[0] = new DriverPropertyInfo("adb", "adb.exe");
		info[0].name = "adb";
		info[0].description = "full route to adb.exe including the adb.exe file name";
		return info;
	}

	
	public boolean jdbcCompliant() {
		return false;
	}

}
